package com.seqb.common.task;

import cn.hutool.extra.mail.MailUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.seqb.common.config.RedisConfig;
import com.seqb.common.utils.RedisUtils;
import com.seqb.utils.DateUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.util.Date;

/**
 * @author lilinshen
 * @title 苏宁易购红包定时任务
 * @description 请填写相关描述
 * @date 2021/07/21
 */
public class SuNingYiGouHongBaoJob implements Job {
    private static final Logger LOGGER = LoggerFactory.getLogger(SuNingYiGouHongBaoJob.class);
    public static HttpHeaders headers = new HttpHeaders();
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        try {
            headers = new HttpHeaders();
            try {
                Object taskParams = redisUtils.get("taskParams");
                if (null != taskParams) {
                    JSONArray parseArray = JSON.parseArray(taskParams.toString());
                    for (int i = 0; i < parseArray.size(); i++) {
                        JSONObject item = parseArray.getJSONObject(i);
                        String type = item.getString("type");
                        if ("SuNingYiGouHongBaoJob".equals(type)) {
                            JSONArray value = item.getJSONArray("value");
                            for (int j = 0; j < value.size(); j++) {
                                JSONObject jsonObject = value.getJSONObject(j);
                                headers.add(jsonObject.getString("key"), jsonObject.getString("value"));
                            }
                        }
                    }
                }
                LOGGER.info("苏宁易购红包定时任务开始-----------" + DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                checkDoneSign();
                recordSign();
                LOGGER.info("苏宁易购红包定时任务结束-----------" + DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 苏宁易购红包签到任务操作2
     */
    public boolean checkDoneSign() {
        Object flagRedis = redisUtils.get(RedisConfig.COM_PREFIX + this.getClass().getSimpleName());
        try {
            RestTemplate restTemplate = new RestTemplate();
            String requestUrl = "https://ifast.suning.com/luckman/mpapi/luck-web/sign/api/checkDone_sign.do?terminal=mini&channel=ygxcx1001&isLogin=true&memberNo=6200121451";
            HttpMethod httpMethod = HttpMethod.GET;
            HttpEntity httpEntity = new HttpEntity(null, headers);
            ResponseEntity<String> responseEntity = restTemplate.exchange(requestUrl, httpMethod, httpEntity, String.class);
            HttpStatus status = responseEntity.getStatusCode();
            if (status.equals(HttpStatus.OK)) {
                String entityBody = responseEntity.getBody();
                //苏宁易购红包定时任务
                JSONObject entityJson = JSONObject.parseObject(entityBody);
                String respCode = entityJson.getString("respCode");
                if ("1".equals(respCode)) {
                    System.out.println("苏宁易购红包定时任务1：" + entityBody);
                } else {
                    System.out.println("苏宁易购红包定时任务1：" + entityBody);
                    if (null == flagRedis) {
                        //设置一天失效时间的key，每天只发一次邮件通知
                        redisUtils.set(RedisConfig.COM_PREFIX + this.getClass().getSimpleName(), true, 86400);
                        //发送邮件通知苏宁易购红包定时任务失效
                        MailUtil.send("lilinshen@cecjx.com", "苏宁易购红包定时任务", "苏宁易购红包定时任务，用户cookie失效，请及时更新用户cookie信息。", false);
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("苏宁易购红包定时任务执行失败1：" + e.getMessage() + e.getCause());
        }
        return false;
    }

    /**
     * 苏宁易购红包签到任务操作2
     */
    public boolean recordSign() {
        Object flagRedis = redisUtils.get(RedisConfig.COM_PREFIX + this.getClass().getSimpleName());
        try {
            RestTemplate restTemplate = new RestTemplate();
            String requestUrl = "https://ifast.suning.com/luckman/mpapi/luck-web/sign/api/query/detail/record_sign.do?terminal=mini&channel=ygxcx1001";
            HttpMethod httpMethod = HttpMethod.GET;
            HttpEntity httpEntity = new HttpEntity(null, headers);
            ResponseEntity<String> responseEntity = restTemplate.exchange(requestUrl, httpMethod, httpEntity, String.class);
            HttpStatus status = responseEntity.getStatusCode();
            if (status.equals(HttpStatus.OK)) {
                String entityBody = responseEntity.getBody();
                //苏宁易购红包定时任务
                JSONObject entityJson = JSONObject.parseObject(entityBody);
                String respCode = entityJson.getString("respCode");
                if ("1".equals(respCode)) {
                    System.out.println("苏宁易购红包定时任务2：" + entityBody);
                } else {
                    System.out.println("苏宁易购红包定时任务2：" + entityBody);
                    if (null == flagRedis) {
                        //设置一天失效时间的key，每天只发一次邮件通知
                        redisUtils.set(RedisConfig.COM_PREFIX + this.getClass().getSimpleName(), true, 86400);
                        //发送邮件通知苏宁易购红包定时任务失效
                        MailUtil.send("lilinshen@cecjx.com", "苏宁易购红包定时任务", "苏宁易购红包定时任务，用户cookie失效，请及时更新用户cookie信息。", false);
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("苏宁易购红包定时任务执行失败2：" + e.getMessage() + e.getCause());
        }
        return false;
    }
}

